﻿namespace AntdUI_HamburgerMenuTabs.Uc
{
    /// <summary>
    /// 汉堡包菜单 + 多标签页面
    /// </summary>
    public partial class HamburgerMenuTabs : UserControl
    {
        public HamburgerMenuTabs()
        {
            InitializeComponent();

            Load += (s, e) =>
            {
                // 加载菜单折叠/展开状态（用户控件首次显示之后调用，否则宽度计算有问题）
                LoadMenuCollapseStatus();
            };

            panelMenu.Shadow = 5;
            panelMenu.ShadowOpacityAnimation = true;
            panelMenu.ShadowOpacity = 0.2F;
            panelMenu.ShadowOpacityHover = 0.8F;

            panelTabs.Shadow = 5;
            panelTabs.ShadowOpacityAnimation = true;
            panelTabs.ShadowOpacity = 0.2F;
            panelTabs.ShadowOpacityHover = 0.8F;

            tabs1.TypExceed = AntdUI.TabTypExceed.Button;

            InitMenu();
        }

        /// <summary>
        /// 设置菜单项
        /// </summary>
        /// <param name="menus"></param>
        public void SetMenu(List<Common.Models.MenuItem>? menus)
        {
            menu1.SetMenu(menus);
        }

        /// <summary>
        /// 初始化菜单
        /// </summary>
        private void InitMenu()
        {
            SetMenu(null);

            menu1.SetSplitterMenu(splitter1);

            menu1.Menu!.SelectChanged += (s, e) =>
            {
                if (menu1.menuSelectMode == 0)
                {
                    string title = e.Value.Text!;
                    string path = "";
                    string path2 = "";
                    string? svg = "";
                    bool closeable = true;
                    Type? pageType = null;
                    if (e.Value.Tag is Common.Models.MenuItemTag tag)
                    {
                        if (tag.Path != null) path = tag.Path;
                        if (tag.Path2 != null) path2 = tag.Path2;
                        if (tag.PageType != null) pageType = tag.PageType;
                        svg = e.Value.IconSvg;
                        closeable = tag.Closeable;
                    }

                    LoadTabPage(title, path, path2, pageType, svg, closeable);
                }
            };

            // 手动切换页面后定位菜单项
            tabs1.SelectedIndexChanged += (s, e) =>
            {
                if (tabPageSelectMode == 0)
                {
                    MenuLocateAfterTabPageSelected();
                }
            };
        }

        /// <summary>
        /// TabPage 选择模式：0=默认；1=自定义程序控制；
        /// </summary>
        int tabPageSelectMode = 0;

        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="title"></param>
        /// <param name="path"></param>
        /// <param name="path2"></param>
        /// <param name="pageType"></param>
        private void LoadTabPage(string title, string path, string path2, Type? pageType, string? svg, bool closeable)
        {
            tabPageSelectMode = 1;

            bool findInstance = false;

            foreach (AntdUI.TabPage _page in tabs1.Pages)
            {
                if (_page.Tag is Common.Models.TabPageTag tag)
                {
                    if (string.Equals(tag.MenuPath, path, StringComparison.OrdinalIgnoreCase))
                    {
                        tabs1.SelectedTab = _page;
                        findInstance = true;
                        break;
                    }
                }
            }

            if (!findInstance)
            {
                AntdUI.TabPage page = new()
                {
                    Text = title,
                    IconSvg = svg,
                    Tag = new Common.Models.TabPageTag(path) { Closeable = closeable },
                };
                if (!closeable)
                {
                    page.ReadOnly = true;
                }
                page.Disposed += (s, e) =>
                {
                    if (ParentForm != null)
                    {
                        AntdUI.Message.info(ParentForm, $"页面【{page.Text}】已关闭。");
                    }
                };

                AntdUI.Panel panel = new()
                {
                    Dock = DockStyle.Fill,
                };

                AntdUI.Panel panelPage = new()
                {
                    Dock = DockStyle.Fill,
                    Padding = new(5),
                };

                panelPage.Controls.Add(panel);
                page.Controls.Add(panelPage);

                if (pageType != null)
                {
                    object[] args = [title, path, path2];
                    UserControl pageContent;
                    try
                    {
                        pageContent = (UserControl)Activator.CreateInstance(pageType, args)!;
                    }
                    catch
                    {
                        pageContent = (UserControl)Activator.CreateInstance(pageType)!;
                    }
                    pageContent.Dock = DockStyle.Fill;
                    panel.Controls.Add(pageContent);
                }
                else
                {
                    var alert = new AntdUI.Alert()
                    {
                        TextTitle = "警告",
                        Text = "菜单未配置关联页面！",
                        Icon = AntdUI.TType.Warn,
                        Height = 100,
                        Dock = DockStyle.Top,
                    };
                    panel.Padding = new(10);
                    panel.Controls.Add(alert);
                }

                tabs1.Pages.Add(page);
                tabs1.SelectedTab = page;
            }

            tabPageSelectMode = 0;
        }

        public AntdUI.Panel? GetPanelPage()
        {
            if (tabs1.SelectedTab != null)
            {
                var page = tabs1.SelectedTab;
                if (page.Controls.Count > 0)
                {
                    if (page.Controls[0] is AntdUI.Panel panel) return panel;
                }
            }
            return null;
        }

        /// <summary>
        /// 手动切换页面后定位菜单项
        /// </summary>
        private void MenuLocateAfterTabPageSelected()
        {
            AntdUI.TabPage? page = tabs1.SelectedTab;

            if (page != null)
            {
                string path = "";
                if (page.Tag is Common.Models.TabPageTag tag)
                {
                    path = tag.MenuPath!;
                }
                menu1.MenuItemCollapsedAll(null);
                menu1.menuSelectMode = 1;
                menu1.MenuItemSelectOne(path, null);
                menu1.menuSelectMode = 0;
                menu1.Refresh();
            }
        }

        /// <summary>
        /// 菜单默认选中项
        /// </summary>
        public void MenuSelectDefault()
        {
            var item = menu1.Menu!.Items.FirstOrDefault();
            if (item != null)
            {
                string title = item.Text!;
                string path = "";
                string path2 = "";
                string? svg = "";
                bool closeable = true;
                Type? pageType = null;
                if (item.Tag is Common.Models.MenuItemTag tag)
                {
                    if (tag.Path != null) path = tag.Path;
                    if (tag.Path2 != null) path2 = tag.Path2;
                    if (tag.PageType != null) pageType = tag.PageType;
                    svg = item.IconSvg;
                    closeable = tag.Closeable;
                }

                LoadTabPage(title, path, path2, pageType, svg, closeable);
            }
        }

        /// <summary>
        /// 加载菜单折叠/展开状态
        /// </summary>
        public void LoadMenuCollapseStatus()
        {
            menu1.LoadMenuCollapseStatus();
        }
    }
}